const Parse = require('./parse')
const slog = require('./single-line-log').stdout

var Region = Parse.Object.extend('Region')
var regions = []
var district = require('./districts.js')
var provinces = district['100000']
const save = (code, name, level = 1, parent = '') => {
  var r = new Region()
  r.set('code', code)
  r.set('level', level)
  r.set('parentCode', parent)
  r.set('name', name)
  regions.push(r)
}
for (var pk in provinces) {
  if (!pk) continue
  save(pk, provinces[pk])
  var cities = district[pk]
  for (var ck in cities) {
    if (!ck) continue
    save(ck, cities[ck], 2, pk)
    var areas = district[ck]
    for (var ak in areas) {
      if (!ak) continue
      save(ak, areas[ak], 3, ck)
    }
  }
}

console.log('try to save all', regions.length)

let counter = 0
const loop = () => {
  if (regions[counter]) {
    regions[counter].save()
      .then(r => {
        slog(`saving(${counter++}) ${r.get('code')} ${r.get('name')}`)
        loop()
      })
      .catch(err => console.log(err))
  } else {
    console.log(regions.length, counter)
  }
}

loop()

